<template>
  <el-dialog
    v-model="dialogVisible"
    title="预警规则测试"
    width="900px"
    :close-on-click-modal="false"
  >
    <div class="test-container">
      <!-- 规则信息 -->
      <el-card class="rule-info" shadow="never">
        <template #header>
          <span class="card-title">规则信息</span>
        </template>
        <el-descriptions :column="2" border>
          <el-descriptions-item label="规则名称">{{ ruleData.ruleName }}</el-descriptions-item>
          <el-descriptions-item label="预警类型">
            <el-tag :type="getWarningTypeTagType(ruleData.warningType)">
              {{ getWarningTypeText(ruleData.warningType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="预警级别">
            <el-tag :type="getWarningLevelTagType(ruleData.warningLevel)">
              {{ getWarningLevelText(ruleData.warningLevel) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="阈值条件">{{ ruleData.threshold }}</el-descriptions-item>
        </el-descriptions>
      </el-card>

      <!-- 测试配置 -->
      <el-card class="test-config" shadow="never">
        <template #header>
          <span class="card-title">测试配置</span>
        </template>
        <el-form :model="testForm" :inline="true" label-width="100px">
          <el-form-item label="测试模式">
            <el-radio-group v-model="testForm.testMode">
              <el-radio value="manual">手动输入</el-radio>
              <el-radio value="historical">历史数据</el-radio>
              <el-radio value="simulation">模拟数据</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="测试时间范围" v-if="testForm.testMode !== 'manual'">
            <el-date-picker
              v-model="testForm.timeRange"
              type="datetimerange"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              style="width: 350px"
            />
          </el-form-item>
        </el-form>

        <!-- 手动输入模式 -->
        <div v-if="testForm.testMode === 'manual'" class="manual-input">
          <h4>输入测试数据</h4>
          <el-row :gutter="20">
            <el-col :span="8" v-for="(param, index) in testParameters" :key="index">
              <el-form-item :label="param.label">
                <el-input
                  v-model="param.value"
                  :placeholder="`请输入${param.label}`"
                  type="number"
                >
                  <template #append>{{ param.unit }}</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <!-- 历史数据模式 -->
        <div v-if="testForm.testMode === 'historical'" class="historical-data">
          <h4>选择历史数据源</h4>
          <el-form :inline="true">
            <el-form-item label="监测站点">
              <el-select v-model="testForm.station" placeholder="请选择监测站点" style="width: 200px">
                <el-option label="主坝监测站" value="main_dam" />
                <el-option label="副坝监测站" value="sub_dam" />
                <el-option label="溢洪道监测站" value="spillway" />
                <el-option label="进水口监测站" value="intake" />
              </el-select>
            </el-form-item>
            <el-form-item label="数据间隔">
              <el-select v-model="testForm.interval" placeholder="请选择数据间隔" style="width: 150px">
                <el-option label="1分钟" value="1min" />
                <el-option label="5分钟" value="5min" />
                <el-option label="10分钟" value="10min" />
                <el-option label="30分钟" value="30min" />
                <el-option label="1小时" value="1hour" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <!-- 模拟数据模式 -->
        <div v-if="testForm.testMode === 'simulation'" class="simulation-data">
          <h4>模拟数据配置</h4>
          <el-form :inline="true">
            <el-form-item label="数据点数">
              <el-input-number v-model="testForm.dataPoints" :min="10" :max="1000" />
            </el-form-item>
            <el-form-item label="变化趋势">
              <el-select v-model="testForm.trend" placeholder="请选择变化趋势" style="width: 150px">
                <el-option label="递增" value="increase" />
                <el-option label="递减" value="decrease" />
                <el-option label="波动" value="fluctuate" />
                <el-option label="随机" value="random" />
              </el-select>
            </el-form-item>
            <el-form-item label="噪声水平">
              <el-select v-model="testForm.noiseLevel" placeholder="请选择噪声水平" style="width: 150px">
                <el-option label="无噪声" value="none" />
                <el-option label="低噪声" value="low" />
                <el-option label="中噪声" value="medium" />
                <el-option label="高噪声" value="high" />
              </el-select>
            </el-form-item>
          </el-form>
        </div>

        <div class="test-actions">
          <el-button type="primary" @click="startTest" :loading="testLoading">
            <el-icon><VideoPlay /></el-icon>
            开始测试
          </el-button>
          <el-button @click="stopTest" :disabled="!testRunning">
            <el-icon><VideoPause /></el-icon>
            停止测试
          </el-button>
          <el-button @click="clearResults">
            <el-icon><Delete /></el-icon>
            清空结果
          </el-button>
        </div>
      </el-card>

      <!-- 测试结果 -->
      <el-card class="test-results" shadow="never" v-if="testResults.length > 0">
        <template #header>
          <div class="result-header">
            <span class="card-title">测试结果</span>
            <div class="result-stats">
              <el-tag type="success">通过: {{ passCount }}</el-tag>
              <el-tag type="danger">触发: {{ triggerCount }}</el-tag>
              <el-tag type="info">总计: {{ testResults.length }}</el-tag>
            </div>
          </div>
        </template>

        <!-- 结果图表 -->
        <div class="result-chart">
          <div ref="chartRef" class="chart-container" v-loading="chartLoading"></div>
        </div>

        <!-- 结果表格 -->
        <el-table :data="testResults" stripe border max-height="300" class="result-table">
          <el-table-column prop="timestamp" label="时间" width="160" />
          <el-table-column prop="inputValue" label="输入值" width="120" />
          <el-table-column prop="threshold" label="阈值" width="120" />
          <el-table-column prop="result" label="测试结果" width="100">
            <template #default="{ row }">
              <el-tag :type="row.result === 'pass' ? 'success' : 'danger'">
                {{ row.result === 'pass' ? '通过' : '触发' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="message" label="消息内容" show-overflow-tooltip />
          <el-table-column prop="notificationSent" label="通知发送" width="100">
            <template #default="{ row }">
              <el-icon v-if="row.notificationSent" color="#67c23a"><CircleCheck /></el-icon>
              <el-icon v-else color="#f56c6c"><CircleClose /></el-icon>
            </template>
          </el-table-column>
        </el-table>
      </el-card>

      <!-- 性能分析 -->
      <el-card class="performance-analysis" shadow="never" v-if="performanceData">
        <template #header>
          <span class="card-title">性能分析</span>
        </template>
        <el-row :gutter="20">
          <el-col :span="6">
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.avgResponseTime }}ms</div>
              <div class="performance-label">平均响应时间</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.maxResponseTime }}ms</div>
              <div class="performance-label">最大响应时间</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.accuracy }}%</div>
              <div class="performance-label">准确率</div>
            </div>
          </el-col>
          <el-col :span="6">
            <div class="performance-item">
              <div class="performance-value">{{ performanceData.throughput }}</div>
              <div class="performance-label">吞吐量/秒</div>
            </div>
          </el-col>
        </el-row>
      </el-card>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">关闭</el-button>
        <el-button type="success" @click="exportResults" :disabled="testResults.length === 0">
          <el-icon><Download /></el-icon>
          导出结果
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, onMounted, onUnmounted, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import {
  VideoPlay,
  VideoPause,
  Delete,
  Download,
  CircleCheck,
  CircleClose
} from '@element-plus/icons-vue'
import * as echarts from 'echarts'

interface Props {
  visible: boolean
  ruleData?: any
}

interface Emits {
  (e: 'update:visible', visible: boolean): void
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  ruleData: () => ({})
})

const emit = defineEmits<Emits>()

const chartRef = ref<HTMLDivElement>()
const chartInstance = ref<echarts.ECharts>()
const testLoading = ref(false)
const chartLoading = ref(false)
const testRunning = ref(false)

const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 测试表单
const testForm = reactive({
  testMode: 'manual',
  timeRange: [],
  station: '',
  interval: '5min',
  dataPoints: 100,
  trend: 'increase',
  noiseLevel: 'low'
})

// 测试参数
const testParameters = ref([
  { label: '水位', value: '', unit: 'm' },
  { label: '流量', value: '', unit: 'm³/s' },
  { label: '降雨量', value: '', unit: 'mm' }
])

// 测试结果
const testResults = ref([])

// 性能数据
const performanceData = ref(null)

// 统计数据
const passCount = computed(() => testResults.value.filter(item => item.result === 'pass').length)
const triggerCount = computed(() => testResults.value.filter(item => item.result === 'trigger').length)

// 获取预警类型标签类型
const getWarningTypeTagType = (type: string) => {
  const typeMap = {
    water_level: 'primary',
    flow: 'success',
    rainfall: 'info',
    capacity: 'warning',
    comprehensive: 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取预警类型文本
const getWarningTypeText = (type: string) => {
  const typeMap = {
    water_level: '水位预警',
    flow: '流量预警',
    rainfall: '降雨预警',
    capacity: '库容预警',
    comprehensive: '综合预警'
  }
  return typeMap[type] || type
}

// 获取预警级别标签类型
const getWarningLevelTagType = (level: string) => {
  const levelMap = {
    blue: 'info',
    yellow: 'warning',
    orange: '',
    red: 'danger'
  }
  return levelMap[level] || 'info'
}

// 获取预警级别文本
const getWarningLevelText = (level: string) => {
  const levelMap = {
    blue: '蓝色预警',
    yellow: '黄色预警',
    orange: '橙色预警',
    red: '红色预警'
  }
  return levelMap[level] || level
}

// 开始测试
const startTest = async () => {
  testLoading.value = true
  testRunning.value = true
  
  try {
    // 根据测试模式生成测试数据
    const testData = generateTestData()
    
    // 执行测试
    await executeTest(testData)
    
    // 更新图表
    updateChart()
    
    // 计算性能数据
    calculatePerformance()
    
    ElMessage.success('测试完成')
  } catch (error) {
    ElMessage.error('测试失败')
  } finally {
    testLoading.value = false
    testRunning.value = false
  }
}

// 停止测试
const stopTest = () => {
  testRunning.value = false
  ElMessage.info('测试已停止')
}

// 清空结果
const clearResults = () => {
  testResults.value = []
  performanceData.value = null
  if (chartInstance.value) {
    chartInstance.value.clear()
  }
}

// 生成测试数据
const generateTestData = () => {
  const data = []
  const now = new Date()
  
  if (testForm.testMode === 'manual') {
    // 手动输入模式
    data.push({
      timestamp: now.toISOString(),
      values: testParameters.value.reduce((acc, param) => {
        acc[param.label] = parseFloat(param.value) || 0
        return acc
      }, {})
    })
  } else if (testForm.testMode === 'simulation') {
    // 模拟数据模式
    for (let i = 0; i < testForm.dataPoints; i++) {
      const timestamp = new Date(now.getTime() + i * 60000).toISOString()
      const baseValue = 100
      let value = baseValue
      
      switch (testForm.trend) {
        case 'increase':
          value = baseValue + i * 2
          break
        case 'decrease':
          value = baseValue - i * 2
          break
        case 'fluctuate':
          value = baseValue + Math.sin(i * 0.1) * 20
          break
        case 'random':
          value = baseValue + (Math.random() - 0.5) * 40
          break
      }
      
      // 添加噪声
      const noiseLevel = {
        none: 0,
        low: 0.05,
        medium: 0.1,
        high: 0.2
      }[testForm.noiseLevel] || 0
      
      value += (Math.random() - 0.5) * value * noiseLevel
      
      data.push({
        timestamp,
        values: { '水位': value }
      })
    }
  }
  
  return data
}

// 执行测试
const executeTest = async (testData) => {
  const results = []
  
  for (const dataPoint of testData) {
    // 模拟规则评估
    const inputValue = dataPoint.values['水位'] || 0
    const threshold = 185.5 // 从规则中获取阈值
    const result = inputValue > threshold ? 'trigger' : 'pass'
    
    results.push({
      timestamp: new Date(dataPoint.timestamp).toLocaleString(),
      inputValue: inputValue.toFixed(2),
      threshold: threshold.toString(),
      result,
      message: result === 'trigger' ? `水位${inputValue.toFixed(2)}m超过阈值${threshold}m` : '正常',
      notificationSent: result === 'trigger'
    })
    
    // 模拟处理延迟
    await new Promise(resolve => setTimeout(resolve, 10))
  }
  
  testResults.value = results
}

// 更新图表
const updateChart = () => {
  if (!chartInstance.value || testResults.value.length === 0) return
  
  chartLoading.value = true
  
  const option = {
    title: {
      text: '测试结果趋势图',
      left: 'center'
    },
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: ['输入值', '阈值', '触发点']
    },
    xAxis: {
      type: 'category',
      data: testResults.value.map(item => item.timestamp.split(' ')[1])
    },
    yAxis: {
      type: 'value',
      name: '数值'
    },
    series: [
      {
        name: '输入值',
        type: 'line',
        data: testResults.value.map(item => parseFloat(item.inputValue)),
        itemStyle: { color: '#409eff' }
      },
      {
        name: '阈值',
        type: 'line',
        data: testResults.value.map(item => parseFloat(item.threshold)),
        lineStyle: { type: 'dashed' },
        itemStyle: { color: '#e6a23c' }
      },
      {
        name: '触发点',
        type: 'scatter',
        data: testResults.value
          .map((item, index) => item.result === 'trigger' ? [index, parseFloat(item.inputValue)] : null)
          .filter(item => item !== null),
        itemStyle: { color: '#f56c6c' },
        symbolSize: 8
      }
    ]
  }
  
  chartInstance.value.setOption(option, true)
  chartLoading.value = false
}

// 计算性能数据
const calculatePerformance = () => {
  if (testResults.value.length === 0) return
  
  const responseTimes = testResults.value.map(() => Math.random() * 50 + 10) // 模拟响应时间
  const avgResponseTime = Math.round(responseTimes.reduce((a, b) => a + b, 0) / responseTimes.length)
  const maxResponseTime = Math.round(Math.max(...responseTimes))
  const accuracy = Math.round((testResults.value.length / testResults.value.length) * 100) // 模拟准确率
  const throughput = Math.round(testResults.value.length / 10) // 模拟吞吐量
  
  performanceData.value = {
    avgResponseTime,
    maxResponseTime,
    accuracy,
    throughput
  }
}

// 导出结果
const exportResults = () => {
  ElMessage.success('正在导出测试结果...')
  // 实现导出逻辑
}

// 关闭对话框
const handleClose = () => {
  dialogVisible.value = false
}

// 初始化图表
const initChart = () => {
  if (!chartRef.value) return
  
  chartInstance.value = echarts.init(chartRef.value)
}

// 监听对话框显示状态
watch(dialogVisible, (visible) => {
  if (visible) {
    nextTick(() => {
      initChart()
    })
  }
})

// 组件卸载时销毁图表
onUnmounted(() => {
  if (chartInstance.value) {
    chartInstance.value.dispose()
  }
})
</script>

<style scoped>
.test-container {
  max-height: 70vh;
  overflow-y: auto;
}

.rule-info,
.test-config,
.test-results,
.performance-analysis {
  margin-bottom: 20px;
}

.card-title {
  font-size: 16px;
  font-weight: bold;
  color: #333;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.result-stats {
  display: flex;
  gap: 10px;
}

.manual-input h4,
.historical-data h4,
.simulation-data h4 {
  margin: 15px 0 10px 0;
  font-size: 14px;
  color: #666;
}

.test-actions {
  margin-top: 20px;
  text-align: center;
}

.result-chart {
  margin-bottom: 20px;
}

.chart-container {
  width: 100%;
  height: 300px;
}

.result-table {
  margin-top: 20px;
}

.performance-analysis {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
}

.performance-item {
  text-align: center;
  padding: 20px;
}

.performance-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 5px;
}

.performance-label {
  font-size: 14px;
  color: #666;
}

.dialog-footer {
  text-align: right;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.el-descriptions-item__label) {
  font-weight: normal;
}
</style>